package com.tourlaid.mamagerment.ao.pc.impl

import com.tourlaid.mamagerment.ao.pc.LoginAo
import com.tourlaid.mamagerment.enums.TldExceptionEnum
import com.tourlaid.mamagerment.enums.UserTypeEnum
import com.tourlaid.mamagerment.service.UserService
import com.tourlaid.mamagerment.util.MD5Util
import com.tourlaid.mamagerment.util.TldException
import org.springframework.stereotype.Service
import org.springframework.util.StringUtils
import java.util.*
import javax.annotation.Resource

/**
 * Created by xiaoyongge on 2017/7/20.
 */
@Service("loginAo")
class LoginAoImpl : LoginAo {

    @Resource
    val userService: UserService? = null

    override fun loginIn(account: String?, password: String?): Long {
        if (StringUtils.isEmpty(account)) {
            throw TldException(TldExceptionEnum.ACCOUNT_NULL)
        }
        if (StringUtils.isEmpty(password)) {
            throw TldException(TldExceptionEnum.PASSWORD_NULL)
        }
        val user = userService!!.getByAccount(account)
        user ?: throw TldException(TldExceptionEnum.LOGIN_ERROR)
        val passwordMd5 = MD5Util.MD5Encode(password)
        if (!Objects.equals(passwordMd5, user.password)) {
            throw TldException(TldExceptionEnum.LOGIN_ERROR)
        }
        return user.id!!
    }

    override fun adminRegister(account: String?, password: String?): Long {
        return userService!!.register(account, password, UserTypeEnum.ADMIN.code)
    }

}